<template>
  <a-modal :width="1200" v-model="visible" title="任务结果" :footer="null" :destroyOnClose="true" :maskClosable="false">
    <a-spin :spinning="loading">
      <div v-if="resultData">
        <div class="task-name">{{ taskName }}</div>

        <div class="result-container">
          <div class="metrics-section">
            <h3>Metrics</h3>
            <a-table :columns="metricsColumns" :dataSource="resultData.metrics" :pagination="false" size="small" />
          </div>

          <div class="params-section">
            <h3>Parameters</h3>
            <a-table :columns="paramsColumns" :dataSource="resultData.params" :pagination="false" size="small" />
          </div>
        </div>
      </div>
      <a-empty v-else description="暂无结果" />
    </a-spin>
  </a-modal>
</template>

<script>
import { getTaskResult } from '@/api/model'

export default {
  data() {
    return {
      visible: false,
      loading: false,
      taskName: '',
      resultData: null,
      metricsColumns: [
        { title: '指标名称', dataIndex: 'key', key: 'key' },
        { title: '步骤', dataIndex: 'step', key: 'step' },
        {
          title: '时间',
          dataIndex: 'timestamp',
          key: 'timestamp',
          customRender: (text) => new Date(text).toLocaleString(),
        },
        {
          title: '值',
          dataIndex: 'value',
          key: 'value',
          customRender: (text) => Number(text).toFixed(4),
        },
      ],
      paramsColumns: [
        { title: '参数名称', dataIndex: 'key', key: 'key' },
        {
          title: '值',
          dataIndex: 'value',
          key: 'value',
          width: '80%',
          customRender: (text) => {
            return <pre class="param-value">{text}</pre>
          },
        },
      ],
    }
  },
  methods: {
    async showModal(record) {
      console.log(record)
      this.visible = true
      this.taskName = record.taskName
      this.loading = true
      try {
        const response = await getTaskResult({ lastRunResult: record.lastRunResult })
        this.resultData = response
      } catch (error) {
        this.$message.error('获取任务结果失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    closeModal() {
      this.visible = false
      this.resultData = null
    },
  },
}
</script>

<style scoped>
.task-name {
  font-size: 16px;
  margin-bottom: 16px;
  color: #333;
}

.result-container {
  display: flex;
  gap: 24px;
}

.metrics-section,
.params-section {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.metrics-section h3,
.params-section h3 {
  margin-bottom: 8px;
  color: #666;
}

.param-value {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
  background: #f5f5f5;
  padding: 8px;
  margin: 0;
  font-size: 12px;
}

:deep(.ant-table-small) {
  border: 1px solid #f0f0f0;
}
</style>
